package com.totem.admin.service.impl;

import com.totem.admin.service.IEmailService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeMessage;
import java.util.Date;

@Slf4j
@Service
public class EmailServiceImpl implements IEmailService {

    @Autowired
    private JavaMailSender javaMailSender;
    @Value("${mail.from}")
    private String from;
    private String personal = "【METAHOMO】";

    public void sendSimpleMail(String subject, String text, String targetEmail) {
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setSubject(subject);
        mailMessage.setText(text);
        if (StringUtils.isNotBlank(targetEmail) && targetEmail.split(",").length > 1) {
            mailMessage.setTo(targetEmail.split(","));//多个号码发送，该发送会将目标邮件分组发送
        } else {
            mailMessage.setTo(targetEmail);
        }
        mailMessage.setFrom(from);
        javaMailSender.send(mailMessage);
    }

    public void sendSeniorEmail(String to, String subject, String text, Boolean isHtml) {
        System.setProperty("mail.mime.splitlongparameters", "false");
        MimeMessage message = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "utf-8");
            helper.setSubject(subject);
            helper.setFrom(from, personal);
            if (StringUtils.isNotBlank(to) && to.split(",").length > 1) {
                helper.setTo(to.split(","));
            } else {
                helper.setTo(to);
            }
            String content = "";
            if (isHtml) {
                content = "<!DOCTYPE html>\n" +
                        "<html lang=\"en\">\n" +
                        "<head>\n" +
                        "    <meta charset=\"UTF-8\">\n" +
                        "    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n" +
                        "    <title></title>\n" +
                        "</head>\n" +
                        "<body>\n" +
                        "  <div>" + text + "</div>\n" +
                        "</body>\n" +
                        "</html>";
                helper.setText(content, true);
            } else {
                helper.setText(text, false);
            }
            helper.setSentDate(new Date());//邮件发送时间
            log.info("发送邮件成功: {}", text);
        }catch(Exception e){
            log.error("发送邮件错误", e);
        }
        javaMailSender.send(message);
    }
}
